<template>
  <div id="teacherInfoPage">
    <div style="display: flex; justify-content: space-between">
      <!-- 搜索栏 -->
      <a-form layout="inline" :model="searchParam" @finish="doSearch">
        <a-form-item label="姓名">
          <a-input v-model:value="searchParam.teacherName" placeholder="请输入姓名" allow-clear />
        </a-form-item>
        <a-form-item label="工号">
          <a-input v-model:value="searchParam.teacherNumber" placeholder="请输入工号" allow-clear />
        </a-form-item>
        <a-form-item label="所教学科">
          <a-input v-model:value="searchParam.subject" placeholder="请输入所教学科" allow-clear />
        </a-form-item>
        <a-form-item label="就职学校">
          <a-input
            v-model:value="searchParam.schoolName"
            placeholder="请输入就职学校"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit"> 搜索 </a-button>
        </a-form-item>
      </a-form>
      <a-button type="primary" size="large" @click="showAddModel">新增教师</a-button>
    </div>
    <div style="margin-bottom: 32px"></div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'teacherAvatar'">
          <a-image :src="record.teacherAvatar" :width="60" />
        </template>
        <template v-else-if="column.dataIndex === 'gender'">
          {{ record.gender === 0 ? '女' : '男' }}
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH-mm-ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showUpdateModel(record.id)">修改</a-button>
            <a-button type="primary" danger @click="doDelete(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="addModel" title="添加教师" @ok="doAdd">
      <div style="height: 16px"></div>
      <a-form
        :model="formDataAdd"
        name="addTeacher"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item label="姓名" name="teacherName">
          <a-input v-model:value="formDataAdd.teacherName" />
        </a-form-item>
        <a-form-item label="工号" name="teacherNumber">
          <a-input v-model:value="formDataAdd.teacherNumber" />
        </a-form-item>
        <a-form-item label="头像" name="teacherAvatar">
          <a-upload
            list-type="picture-card"
            :show-upload-list="false"
            :custom-request="handleUpload"
            :before-upload="beforeUpload"
          >
            <img
              v-if="formDataAdd?.teacherAvatar"
              :src="formDataAdd?.teacherAvatar"
              alt="avatar"
              style="width: 70px; height: 70px"
            />
            <div v-else>
              <LoadingOutlined v-if="loading"></LoadingOutlined>
              <PlusOutlined v-else></PlusOutlined>
              <div class="ant-upload-text">点击或拖拽上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="性别" name="gender">
          <a-radio-group v-model:value="formDataAdd.gender">
            <a-radio :value="0">女</a-radio>
            <a-radio :value="1">男</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="年龄" name="age">
          <a-input-number v-model:value="formDataAdd.age" :min="18" :max="100" />
        </a-form-item>
        <a-form-item label="所教学科" name="subject">
          <a-auto-complete
            v-model:value="formDataAdd.subject"
            :options="courseList.map((item) => ({ value: item.courseName }))"
            @change="onCourseChange"
            placeholder="请输入所教学科"
          />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formDataAdd.phone" />
        </a-form-item>
        <a-form-item label="就职学校" name="schoolName">
          <a-input v-model:value="formDataAdd.schoolName" />
        </a-form-item>
        <a-form-item label="简介" name="introduction">
          <a-textarea v-model:value="formDataAdd.introduction" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:open="updateModel" title="更新教师信息" @ok="doUpdate">
      <div style="height: 16px"></div>
      <a-form
        :model="formDataUpdate"
        name="updateTeacher"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item label="姓名" name="teacherName">
          <a-input v-model:value="formDataUpdate.teacherName" />
        </a-form-item>
        <a-form-item label="工号" name="teacherNumber">
          <a-input v-model:value="formDataUpdate.teacherNumber" />
        </a-form-item>
        <a-form-item label="头像" name="teacherAvatar">
          <a-upload
            list-type="picture-card"
            :show-upload-list="false"
            :custom-request="handleUpload"
            :before-upload="beforeUpload"
          >
            <img
              v-if="formDataUpdate?.teacherAvatar"
              :src="formDataUpdate?.teacherAvatar"
              alt="avatar"
              style="width: 70px; height: 70px"
            />
            <div v-else>
              <LoadingOutlined v-if="loading" />
              <PlusOutlined v-else></PlusOutlined>
              <div class="ant-upload-text">点击或拖拽上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="性别" name="gender">
          <a-radio-group v-model:value="formDataUpdate.gender">
            <a-radio :value="0">女</a-radio>
            <a-radio :value="1">男</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="年龄" name="age">
          <a-input-number v-model:value="formDataUpdate.age" :min="18" :max="100" />
        </a-form-item>
        <a-form-item label="所教学科" name="subject">
          <a-auto-complete
            v-model:value="formDataUpdate.subject"
            :options="courseList.map((item) => ({ value: item.courseName }))"
            @change="onCourseChange"
            placeholder="请输入所教学科"
          />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formDataUpdate.phone" />
        </a-form-item>
        <a-form-item label="就职学校" name="schoolName">
          <a-input v-model:value="formDataUpdate.schoolName" />
        </a-form-item>
        <a-form-item label="简介" name="introduction">
          <a-textarea v-model:value="formDataUpdate.introduction" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import { message, type UploadProps } from 'ant-design-vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import {
  addTeacherUsingPost,
  deleteTeacherUsingPost,
  getTeacherByIdUsingGet,
  listTeacherByPageUsingPost,
  updateTeacherUsingPost,
} from '@/api/teacherController.ts'
import { uploadImageUsingPost } from '@/api/fileUploadController.ts'
import { listCourseUsingPost } from '@/api/courseController.ts'

const addModel = ref<boolean>(false)
const updateModel = ref<boolean>(false)

const columns = [
  {
    title: '姓名',
    dataIndex: 'teacherName',
  },
  {
    title: '工号',
    dataIndex: 'teacherNumber',
  },
  {
    title: '头像',
    dataIndex: 'teacherAvatar',
  },
  {
    title: '性别',
    dataIndex: 'gender',
  },
  {
    title: '年龄',
    dataIndex: 'age',
  },
  {
    title: '所教学科',
    dataIndex: 'subject',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
  },
  {
    title: '就职学校',
    dataIndex: 'schoolName',
  },
  // {
  //   title: '简介',
  //   dataIndex: 'userProfile',
  // },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据
const dataList = ref<API.Teacher[]>([])
const total = ref(0)

// 搜索条件
const searchParam = reactive<API.TeacherQueryRequest>({
  current: 1,
  pageSize: 10,
  teacherNumber: '',
  teacherName: '',
  subject: '',
  schoolName: '',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParam.current,
    pageSize: searchParam.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共${total}条`,
  }
})

const doTableChange = (page: any) => {
  searchParam.current = page.current
  searchParam.pageSize = page.pageSize
  fetchData()
}

// 获取数据
const fetchData = async () => {
  const res = await listTeacherByPageUsingPost({
    ...searchParam,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

const courseList = ref<API.Course[]>([])
const fetchCourseList = async () => {
  const res = await listCourseUsingPost({})
  if (res.data.code === 0 && res.data.data) {
    courseList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

// 页面加载时获取数据，请求一次
onMounted(() => {
  fetchData()
  fetchCourseList()
})

const onCourseChange = async (value: string) => {
  const res = await listCourseUsingPost({
    courseName: value,
  })
  if (res.data.code === 0 && res.data.data) {
    courseList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

const doSearch = () => {
  // 重置页码
  searchParam.current = 1
  fetchData()
}

const doDelete = async (id: number) => {
  if (!id) {
    return
  }
  const res = await deleteTeacherUsingPost({ id: id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}

const formDataAdd = reactive<API.TeacherAddRequest>({
  teacherName: '',
  teacherNumber: '',
  teacherAvatar: '',
  gender: undefined,
  age: undefined,
  subject: '',
  phone: '',
  schoolName: '',
  introduction: '',
})
const formDataUpdate = ref<API.TeacherUpdateRequest>({
  teacherName: '',
  teacherNumber: '',
  teacherAvatar: '',
  gender: undefined,
  age: undefined,
  subject: '',
  phone: '',
  schoolName: '',
  introduction: '',
})

const doUpdate = async () => {
  const res = await updateTeacherUsingPost({
    ...formDataUpdate.value,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('更新成功')
    fetchData()
    updateModel.value = false
  } else {
    message.error('更新失败, ' + res.data.message)
  }
}

const doAdd = async () => {
  const res = await addTeacherUsingPost({
    ...formDataAdd,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('添加成功')
    fetchData()
    addModel.value = false
  } else {
    message.error('添加失败, ' + res.data.message)
  }
}

const showAddModel = () => {
  formDataAdd.teacherName = ''
  formDataAdd.teacherNumber = ''
  formDataAdd.teacherAvatar = ''
  formDataAdd.gender = undefined
  formDataAdd.age = undefined
  formDataAdd.subject = ''
  formDataAdd.phone = ''
  formDataAdd.schoolName = ''
  formDataAdd.introduction = ''
  fetchCourseList()
  addModel.value = true
}

const showUpdateModel = async (id: number) => {
  const res = await getTeacherByIdUsingGet({ id })
  if (res.data.code === 0 && res.data.data !== null) {
    formDataUpdate.value = {
      ...res.data.data,
    }
    updateModel.value = true
  } else {
    message.error('获取数据失败, ' + res.data.message)
  }
}

const loading = ref<boolean>(false)

/**
 * 上传图片
 * @param file
 */
const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const res = await uploadImageUsingPost({}, file)
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      formDataAdd.teacherAvatar = res.data.data
      formDataUpdate.value.teacherAvatar = res.data.data
    } else {
      message.error('图片上传失败，' + res.data.message)
    }
  } catch (error) {
    console.log('图片上传失败，' + error)
    message.error('图片上传失败，' + error)
  }
  loading.value = false
}

/**
 * 上传前的校验
 * @param file
 */
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  // 校验图片格式
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，推荐 jpg 或 png')
  }
  // 校验图片大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('不能上传超过 2M 的图片')
  }
  return isJpgOrPng && isLt2M
}
</script>

<style scoped></style>
